package com.xz.xzutils.test;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.LightVirtualFile;

public class MyEditor {
    public static Editor createEditor(Project project) {
        EditorFactory editorFactory = EditorFactory.getInstance();
        String code= """
                // 创建 Document
                        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
                
                        // 创建 Editor 实例
                        Editor editor = editorFactory.createEditor(document, project);
                
                        // 启用代码折叠
                        editor.getSettings().setFoldingOutlineShown(true);
                
                        // 设置高亮（根据文件类型自动应用）
                        ((EditorEx) editor).setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(project, virtualFile));
                
                        // 启用行号
                        editor.getSettings().setLineNumbersShown(true);
                """;
        // 创建虚拟文件
        LightVirtualFile virtualFile = new LightVirtualFile("test.log");
         //LightVirtualFile virtualFile = new LightVirtualFile("Demo.json", JsonLanguage.INSTANCE, code);

        // 创建 Document
        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);

        // 创建 Editor 实例
        Editor editor = editorFactory.createEditor(document, project);

        // 启用代码折叠
        editor.getSettings().setFoldingOutlineShown(true);

        // 设置高亮（根据文件类型自动应用）
        ((EditorEx) editor).setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(project, virtualFile));

        // 启用行号
        editor.getSettings().setLineNumbersShown(true);

        // 启用滚动条
        editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
        return editor;
    }

    public void test2(Project project) {
        // 窗口关闭时释放资源
        //Disposer.register(myDisposable, () -> {
        //    EditorFactory.getInstance().releaseEditor(editor);
        //    FileDocumentManager.getInstance().releaseDocument(document);
        //});
    }
}
